package com.yami.shop.search.common.util;

import com.yami.shop.bean.vo.search.*;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.util.EsPageVO;
import com.yami.shop.common.util.Json;
import com.yami.shop.search.common.constant.EsConstant;
import com.yami.shop.search.common.param.EsPageParam;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.ParsedTopHits;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author YXF
 * @date 2021/07/29
 */
@Component
public class SearchResponseUtil {

    /**
     *
     */
    public static EsProductSearchVO getProductSearch(SearchResponse response) {

        // 1、返回的所有查询到的商品
        EsProductSearchVO esProductSearchVO = new EsProductSearchVO();
        //===============spu列表信息====================//
        esProductSearchVO.setProducts(buildSpuSearchList(response.getHits()));

        //===============聚合信息====================//
        Aggregations aggregations = response.getAggregations();
        if (Objects.nonNull(aggregations)) {
            processingAggregationsData(esProductSearchVO,aggregations);
        }

        return esProductSearchVO;
    }

    /**
     * 从es返回的数据中获取spu列表
     * @param hits es返回的数据
     * @return
     */
    public static List<ProductSearchVO> buildSpuSearchList(SearchHits hits) {
        List<ProductSearchVO> prodList = new ArrayList<>();
        for (SearchHit hit : hits.getHits()) {
            String json = hit.getSourceAsString();
            ProductSearchVO productSearchVO = Json.parseObject(json, ProductSearchVO.class);
            prodList.add(productSearchVO);
        }
        return prodList;
    }
    /**
     * 处理聚合数据
     * @param aggregations
     */
    private static void processingAggregationsData(EsProductSearchVO esProductSearchVO, Aggregations aggregations) {
        //===============品牌信息====================//
        ParsedNested brandNested = aggregations.get(EsConstant.BRAND);
        if (Objects.nonNull(brandNested)) {
            List<String> brandJson = handleAggregations(brandNested, EsConstant.BRAND_ID);

            for (String json : brandJson) {
                BrandSearchVO brandSearchVO = Json.parseObject(json, BrandSearchVO.class);
                esProductSearchVO.getBrands().add(brandSearchVO);
            }
        }
        //===============分类信息====================//
        loadCategoryAggregationsData(esProductSearchVO, aggregations);

        //===============店铺信息====================//
        ParsedLongTerms shopTerms = aggregations.get(EsConstant.SHOP);
        if (Objects.nonNull(shopTerms)) {
            List<? extends Terms.Bucket> shopBuckets = shopTerms.getBuckets();
            for (Terms.Bucket bucket : shopBuckets) {
                esProductSearchVO.setShopInfo(new ShopSearchVO());
                esProductSearchVO.getShopInfo().setShopId(Long.valueOf(bucket.getKey().toString()));
            }
        }
    }

    private static void loadCategoryAggregationsData(EsProductSearchVO esProductSearchVO, Aggregations aggregations) {
        String categoryId = null;
        ParsedNested categoriesNested = null;
        // 平台分类
        if (Objects.nonNull(aggregations.get(EsConstant.CATEGORY))) {
            categoryId = EsConstant.CATEGORY_ID;
            categoriesNested = aggregations.get(EsConstant.CATEGORY);
        }
        if (Objects.nonNull(categoriesNested)) {
            esProductSearchVO.setCategories(new ArrayList<>());
            List<String> categoryJson = handleAggregations(categoriesNested, categoryId);
            for (String json : categoryJson) {
                CategorySearchVO categorySearchVO = Json.parseObject(json, CategorySearchVO.class);
                esProductSearchVO.getCategories().add(categorySearchVO);
            }
        }
    }





    /**************************************  基础接口   *************************************/

    /**
     * 处理聚合数据
     * @param brandNested
     * @return
     */
    public static List<String> handleAggregations(ParsedNested brandNested, String id) {
        List<String> dataList = new ArrayList<>();
        ParsedLongTerms brandLongTerms = brandNested.getAggregations().get(id);
        List<? extends Terms.Bucket> buckets = brandLongTerms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            ParsedTopHits parsedTopHits = bucket.getAggregations().get(EsConstant.TOP_HITS_DATA);
            for (SearchHit hit : parsedTopHits.getHits().getHits()) {
                String sourceAsString = hit.getSourceAsString();
                dataList.add(sourceAsString);
            }
        }
        return dataList;
    }

    /**
     * 构建分页数据
     * @param pageParam
     * @param esPageVO
     * @param response
     */
    public static void buildSearchPage(EsPageParam pageParam, EsPageVO<?> esPageVO, SearchResponse response) {
        //总记录数
        long total = response.getHits().getTotalHits().value;
        esPageVO.setTotal(total);
        // 总页码
        int totalPages = (int)total % pageParam.getSize() == 0 ?
                (int)total / pageParam.getSize() : ((int)total / pageParam.getSize() + 1);
        esPageVO.setPages(totalPages);
    }

}
